﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace System.Erp.Runtime.Composition
{
    /// <summary>
    /// 通过一个Type创建的一个包对象
    /// </summary>
    public class TypeCatalog : PartCatalogBase
    {
        /// <summary>
        /// 创建 TypeCatalog 实例
        /// </summary>
        /// <param name="type">要包装的类对象</param>
        public TypeCatalog(Type type)
        {
            #region 参数检查
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            #endregion
            this.Type = type;
        }

        /// <summary>
        /// 返回此组合所在的类实例
        /// </summary>
        public Type Type { get; private set; }

        /// <summary>
        /// 创建类关联的零件集合
        /// </summary>
        /// <returns>类关联的零件集合</returns>
        protected override ReadOnlyCollection<Tuple<PartAction, IPart>> CreateParts()
        {
            List<Tuple<PartAction,IPart>> parts = new List<Tuple<PartAction,IPart>>();
            AttributeReflectedSource refSource = new AttributeReflectedSource(this.Type);
            IPart part;

            foreach (PartProviderAttribute att in refSource.Attributes.OfType<PartProviderAttribute>())
            {
                part = att.CreatePart(refSource);
                if (part != null)
                {
                    parts.Add(Tuple.Create(PartAction.Apply, part));
                }
            }
            return parts.AsReadOnly();
        }

        /// <summary>
        /// 返回空的分组，类没有下级了。
        /// </summary>
        /// <returns>空的分组对象</returns>
        protected override ReadOnlyCollection<Tuple<PartAction, IPartCatalog>> CreateCatalogs()
        {
            return EmptyCatalogs;
        }
    }
}
